//  UploadingHeadimgeVC.m
//  XJMTechnician
//  Created by 洗脚么_one on 2017/12/4.
//  Copyright © 2017年 Mr.hu. All rights reserved.
//

#import "UploadingHeadimgeVC.h"

@interface UploadingHeadimgeVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *Change_HeadImage;
@property (weak, nonatomic) IBOutlet UIButton *UploadingComplitebtn;
/** 注释 **/
@property (strong, nonatomic) UIImagePickerController * pickController;
@property (nonatomic,strong)  UIImage * headImage;
@property (nonatomic,strong)  NSData * headdata;
@property (nonatomic,copy) NSString * teach_descs;
@property(nonatomic,copy)Uploadhead UploadBlock;

@property (weak, nonatomic) IBOutlet UIButton *Headimage_Circle;

@end

@implementation UploadingHeadimgeVC

-(instancetype)initWithBlock:(Uploadhead)UploadBlock
{
    if (self = [super init]) {
        self.UploadBlock = UploadBlock;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addLeftBtn:[UIImage imageNamed:@"fanhui"] Action:@selector(backToPrevious)];
    self.title = @"上传头像";
    
    self.UploadingComplitebtn.layer.cornerRadius = 22;
    self.UploadingComplitebtn.layer.masksToBounds = YES;
    
    self.Headimage_Circle.layer.cornerRadius = 35;
    self.Headimage_Circle.layer.masksToBounds = YES;
    
    self.pickController = [[UIImagePickerController alloc]init];
    self.pickController.allowsEditing = YES;
    self.pickController.delegate = self;
    
}

- (IBAction)ChangeUploadHeadImageMeth:(id)sender {
    
    [self selectHeadImage];
}

- (IBAction)ComliteUploadServiceMeth:(id)sender {
    
    self.UploadBlock(@"头像已上传成功");
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)selectHeadImage
{
    UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"选取照片" message:nil preferredStyle:0];
    UIAlertAction * actionone = [UIAlertAction actionWithTitle:@"照片库" style:0 handler:^(UIAlertAction *action) {
        
        self.pickController.sourceType = UIImagePickerControllerCameraCaptureModePhoto;
        [self presentViewController:self.pickController animated:YES completion:^{
            
        }];
    }];
    
    UIAlertAction * actiontwo = [UIAlertAction actionWithTitle:@"拍照" style:0 handler:^(UIAlertAction *action) {
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"该设备不存在摄像功能或摄像已损坏！" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [a addAction:act];
            [self presentViewController:a animated:YES completion:nil];
            
        }else
        {
            self.pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.pickController animated:YES completion:nil];
        }
        
    }];
    UIAlertAction * actionthree = [UIAlertAction actionWithTitle:@"胶卷" style:0 handler:^(UIAlertAction *action) {
        self.pickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:self.pickController animated:YES completion:nil];
    }];
    UIAlertAction * actionfour = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction *action) {
    }];
    
    [aler addAction:actionone];
    [aler addAction:actiontwo];
    [aler addAction:actionthree];
    [aler addAction:actionfour];
    
    [self presentViewController:aler animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        [self.Change_HeadImage setImage:info[UIImagePickerControllerEditedImage] forState:UIControlStateNormal];
    }];
    
    self.headImage = info[UIImagePickerControllerEditedImage];
    
    
    [XJHttpClass ReceiveQiniuTokenFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            
            NSDictionary * datadict = response[@"data"];
            NSString * qiniu_token = datadict[@"upToken"];
            
            self.headdata = UIImagePNGRepresentation(self.headImage);
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"YYYYMMddHHmmss"];
            NSDate *datenow = [NSDate date];
            
            NSString *currentTimeString = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:datenow]];
            QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:@"text/plain" progressHandler:nil params:@{ @"x:foo":@"fooval" } checkCrc:YES cancellationSignal:nil];
            
            __block QNResponseInfo *testInfo = nil;
            __block NSDictionary *testResp = nil;
            
            
            [upManager putData:self.headdata key:currentTimeString token:qiniu_token
                      complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                          
                          [LoadingView hide];
                          testInfo = info;
                          testResp = resp;
                          
                          NSString * Identity_Fontet = [NSString stringWithFormat:@"%@/%@",kQiniuBaseUrl,resp[@"key"]];
                          [XJHttpClass FixTeachHeadImageToken:qiniu_token headurl:Identity_Fontet andFinishblock:^(id response, NSString *errStr) {
                              
                              if (errStr) {
                                  [XJToolClass tipAnimationWith:errStr];
                              }else{
                                  [XJToolClass removeHeadImg];
                                  [XJToolClass saveHeadImg:Identity_Fontet];
                              }
                          }];
                          
                      } option:opt];
            
            if (testInfo.isOK) {
                //给定时
                [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(defaileduploadheadimage) userInfo:nil repeats:NO];
            }
        }
    }];
}

-(void)defaileduploadheadimage{
    
    [LoadingView hide];
    [XJToolClass tipAnimationWith:@"网络连接不稳定,上传失败！"];
}


@end
